﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace RenameFileBatch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn选择目录_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                tb目录.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private readonly Dictionary<string, string> _fileDictionary = new Dictionary<string, string>();

        private void btn全部替换_Click(object sender, EventArgs e)
        {
            if (tb目录.Text.Length == 0 || tb搜索.Text.Length == 0)
            {
                return;
            }
            var files = from file in Directory.EnumerateFiles(tb目录.Text, "*.*",
                            cb修改子目录.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                        where
                            file.IndexOf(tb搜索.Text,
                                cb大小写匹配.Checked ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) != -1
                        select file;

            foreach (var file in files)
            {
                var fileRename = file.Replace(tb搜索.Text, tb替换.Text);
                File.Move(file, fileRename);
                _fileDictionary.Add(file, fileRename);
            }

            MessageBox.Show(@"修改成功，共" + _fileDictionary.Count + @"个文件受影响");
        }

        private void btn全部撤销_Click(object sender, EventArgs e)
        {
            if (_fileDictionary.Count == 0)
            {
                return;
            }
            foreach (var file in _fileDictionary)
            {
                File.Move(file.Value, file.Key);
            }
            _fileDictionary.Clear();
            MessageBox.Show(@"已经全部撤销");
        }
    }
}
